package com.reader.cms.controller.common;

import com.reader.cms.utils.AliOSSUtils;
import com.reader.core.entity.ResultMessageInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * 上传接口
 */
@RestController
@RequestMapping(value = "/api")
public class UploadController {

    @PostMapping("/img/upload")
    public ResultMessageInfo UploadImg(@RequestParam(value = "file",required = false) MultipartFile file) throws Exception {
        String url = "";
        if(file == null || StringUtils.isBlank(file.getOriginalFilename())){
            return ResultMessageInfo.ofMessage("图片文件为空");
        }
        String contentType = file.getContentType();
        if (!contentType.contains("")) {
            return ResultMessageInfo.ofMessage("contentType为空值");
        }
        BufferedImage bufferedImage = ImageIO.read(file.getInputStream());
        int width = bufferedImage.getWidth();
        int height = bufferedImage.getHeight();
        try {
            url = AliOSSUtils.uploadImg2Oss(file);
        } catch (IOException  e) {
            return ResultMessageInfo.ofMessage("图片上传失败！！！");
        }
        return ResultMessageInfo.ofSuccess("图片上传成功！",url);
    }


    @PostMapping("/video/upload")
    public ResultMessageInfo UploadVideo(@RequestParam(value = "file",required = false) MultipartFile file) throws Exception {
        String url = "";
        if(file == null || StringUtils.isBlank(file.getOriginalFilename())){
            return ResultMessageInfo.ofMessage("视频文件为空");
        }
        String contentType = file.getContentType();
        if (!contentType.contains("")) {
            return ResultMessageInfo.ofMessage("contentType为空值");
        }
        try {
            url = AliOSSUtils.uploadImg2Oss(file);
        } catch (IOException  e) {
            return ResultMessageInfo.ofMessage("视频上传失败！！！");
        }
        return ResultMessageInfo.ofSuccess("视频上传成功！",url);
    }


    @PostMapping("/audio/upload")
    public ResultMessageInfo UploadAudio(@RequestParam(value = "file",required = false) MultipartFile file) throws Exception {
        String url = "";
        if(file == null || StringUtils.isBlank(file.getOriginalFilename())){
            return ResultMessageInfo.ofMessage("音频文件为空");
        }
        String contentType = file.getContentType();
        if (!contentType.contains("")) {
            return ResultMessageInfo.ofMessage("contentType为空值");
        }
        try {
            url = AliOSSUtils.uploadImg2Oss(file);
        } catch (IOException  e) {
            return ResultMessageInfo.ofMessage("音频上传失败！！！");
        }
        return ResultMessageInfo.ofSuccess("音频上传成功！",url);
    }

}
